<template>
  <el-auto-resizer style="min-height: 300px; max-height: 500px">
    <template #default="{ height, width }">
      <el-table-v2
        ref="tableRef"
        :columns="columns"
        :data="fileterEventLogs"
        row-class="center"
        :width="width"
        :height="height"
        :footer-height="50"
        fixed
      >
        <template #footer>
          <el-popconfirm
            v-if="fileterEventLogs.length"
            title="请确认是否清空所有保存的事件"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="clear_event"
          >
            <template #reference>
              <el-button v-if="fileterEventLogs.length" type="danger" plain
                >清空事件{{ fileterEventLogs.length }}</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-v2>
    </template>
  </el-auto-resizer>
</template>
<script setup lang="ts">
import store from "~/utils/store";
import type { Column, TableV2Instance, HeaderCellSlotProps } from "element-plus";
import { Filter, SortUp, SortDown } from "@element-plus/icons-vue";
import server_api from "../../utils/server_api";
const config = toRef(store);
const tableRef = ref<TableV2Instance>();
const popoverRef = ref();
const fileterSelectKeys = ref<{
  flag: { [key: string]: boolean };
  event: { [key: string]: boolean };
  sort: boolean;
}>({ flag: {}, event: {}, sort: true });

interface log_event {
  time: number;
  flag: number;
  event: number;
  state: number;
  [key: string]: number;
}
const event2str = [
  "无效事件",
  "充电开关",
  "放电开关",
  "放电过流",
  "放电短路",
  "电池欠压",
  "电池过压",
  "充电过流",
  "警报状态",
  "电流传感通",
  "电压传感通",
  "负载",
  "主动均衡",
  "清除警报",
  "更新配置",
  "复位芯片",
  "保存配置",
  "获取配置",
  "AFE 校验",
  "IO  警报",
  "重启",
];
const flag2str = ["AFE触发", "用户触发", "系统触发"];

const key2str = {
  event: event2str,
  flag: flag2str,
};

const event_logs = computed(() => {
  if (config.value.events) return config.value.events;
  return [];
});

const fileterEventLogs = computed(() => {
  let res = event_logs.value;

  if (fileterSelectKeys.value.sort) res = res.slice().reverse();

  let fileterFlag = Object.keys(fileterSelectKeys.value.flag).filter((key) =>
    fileterSelectKeys.value.flag[key] ? true : false
  );
  let fileterEvent = Object.keys(fileterSelectKeys.value.event).filter((key) =>
    fileterSelectKeys.value.event[key] ? true : false
  );
  res = res.filter((item: log_event) => {
    if (fileterFlag.length) {
      if (!fileterFlag.includes(item.flag.toString())) return false;
    }
    return true;
  });
  res = res.filter((item: log_event) => {
    if (fileterEvent.length) {
      if (!fileterEvent.includes(item.event.toString())) return false;
    }
    return true;
  });
  // console.log(res, fileterFlag, fileterEvent);
  return res;
});

const fileterKeys = computed(() => {
  const keys = ["flag", "event"];
  let res: { [key: string]: number[] } = { flag: [], event: [] };
  keys.forEach((key: string) => {
    let arr = event_logs.value.map((item: log_event) => item[key]);
    res[key] = Array.from(new Set(arr));
  });
  // console.log(res);
  return res;
});

function state2TypeFromEvent(data: log_event) {
  if (data.event === 1 || data.event === 2 || data.event === 12)
    return data.state ? "success" : "info";
  if (data.event === 11) return data.state ? "success" : "info";
  return data.state ? "danger" : "success";
}

function state2strFromEvent(data: log_event) {
  if (data.event === 1 || data.event === 2 || data.event === 12)
    return data.state ? "开启" : "关闭";
  if (data.event === 11) return data.state ? "已接入" : "未接入";
  return data.state ? "异常" : "正常";
}

const createFilterList = (key: string) => {
  return h(
    ElPopover,
    {
      ref: popoverRef,
      trigger: "click",
      width: 100,
    },
    {
      default: () =>
        fileterKeys.value[key].map((item: number) =>
          h(
            ElCheckbox,
            {
              value: item,
              onChange: (value) => {
                fileterSelectKeys.value[key][item] = value;
              },
            },
            () => key2str[key][item]
          )
        ),
      reference: () => h(ElIcon, {}, () => h(Filter)),
    }
  );
};

const columns: Column<any>[] = [
  {
    key: "time",
    dataKey: "time",
    title: "时间",
    width: 100,
    align: "center",
    cellRenderer: ({ cellData: time }) =>
      h(ElText, {}, () => new Date(time * 1000).toLocaleString()),
    headerCellRenderer: (props: HeaderCellSlotProps) => {
      return h("div", { style: "display: flex;align-items: center;" }, [
        props.column.title,
        h(
          ElIcon,
          {
            onClick: () => (fileterSelectKeys.value.sort = !fileterSelectKeys.value.sort),
          },
          () => (fileterSelectKeys.value.sort ? h(SortDown) : h(SortUp))
        ),
      ]);
    },
  },
  {
    key: "flag",
    dataKey: "flag",
    title: "标志",
    width: 80,
    align: "center",
    cellRenderer: ({ cellData: flag }) =>
      h(ElTag, { type: flag ? "success" : "info" }, () => flag2str[flag]),
    headerCellRenderer: (props: HeaderCellSlotProps) => {
      return h("div", { style: "display: flex;align-items: center;" }, [
        props.column.title,
        createFilterList("flag"),
      ]);
    },
  },
  {
    key: "event",
    dataKey: "event",
    title: "事件",
    width: 90,
    align: "center",
    cellRenderer: ({ cellData: event }) =>
      h(ElText, {}, () => (event > event2str.length ? "未定义" : event2str[event])),
    headerCellRenderer: (props: HeaderCellSlotProps) => {
      return h("div", { style: "display: flex;align-items: center;" }, [
        props.column.title,
        createFilterList("event"),
      ]);
    },
  },
  {
    key: "state",
    dataKey: "state",
    title: "状态",
    width: 80,
    align: "center",
    cellRenderer: ({ rowData }) =>
      h(ElTag, { type: state2TypeFromEvent(rowData) }, () => state2strFromEvent(rowData)),
  },
];

const clear_event = () => {
  server_api.clear_event();
};
</script>
<style scoped>
:deep(.center),
:deep(.el-table-v2__header-row) {
  justify-content: space-evenly;
}
:deep(.el-table-v2__body) > div:nth-child(1)::-webkit-scrollbar {
  overflow: hidden !important;
  padding: 0 !important;
}
:deep(.el-table-v2__body) > div:nth-child(1) {
  overflow-y: auto !important;
  overflow-x: hidden !important;
  padding: 0 !important;
}
:deep(.el-table-v2__footer) {
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
:deep(.el-empty) {
  padding: 0;
}
</style>
